<?php

include_once "function_xml_basic.php";
include_once "function_xml_atom.php";

$root_path = "/MINI/SECURITY/POLICY/IPMACBIND";
$ifconfig = "/sbin/ifconfig ";
$arp = "/usr/local/sbin/arp ";

function GetXmlBindByMac($m)
{
	$ret_array = GetXmlBindList();
    
        foreach ($ret_array as $ret)
        {   
                if ($ret['Mac'] == $m)
                        return $ret;
        }   
        return NULL;
}

function GetXmlIpMacBindEnabled()
{
	global $root_path;
	$query_string = $root_path;
	$key_array = array("Enabled");
	$list = GetAttributList($query_string, $key_array);
	foreach ($list as $l)
	{
		$ret = $l["Enabled"];
		break;
	}

	return $ret;
}

function SetXmlIpMacBindEnabled($v)
{
	global $root_path;
	$in_array['Enabled'] = $v;
	$query_string = $root_path. "[1]";
	EditAllAttrOfNode($query_string, $in_array);
	ApplySysIpMacBind();
}

function GetXmlBindList()
{
	global $root_path;
	$query_string = $root_path. "/HOST";
	$key_array = array("Ip", "Mac", "Dev", "Enabled", "Type");
	return GetAttributList($query_string, $key_array);
}

function GetXmlNumberBind()
{
	global $root_path;
	$query_string = $root_path. "/HOST";
	return GetNumberOfNode($query_string);
}

function DelXmlSpecialOneBind($m)
{
	global $root_path;

	$query_string = $root_path. "/HOST[@Mac='". $m. "']";
	DelSpecialNode($query_string);
}

function AppendXmlOneBind($in_array)
{
	global $root_path;
        $node_name = "HOST";
	$query_string = $root_path;
	$in_array['Type'] = "1";
	AppendAllAttrOfNode($query_string, $node_name, $in_array);
}

function SetXmlSecOneBind($in_array)
{
	global $root_path;
	$in_array['Type'] = "1";
	$query_string = $root_path. "/HOST[@Mac='". $in_array['Mac']. "']";
	EditAllAttrOfNode($query_string, $in_array);
}

function DelXmlAllBind()
{
	global $root_path;
	$query_string = $root_path. "/HOST";
	DelSpecialNode($query_string);
}

function WriteStringToFile($file, $s)
{
        $handle = fopen($file, "w+");
        if ($handle == FALSE)
        {
		//print "Open file error.";
                return FALSE;
        }

        $ret = fwrite($handle, $s);
	if ($ret === FALSE)
	{
		//print "Write file error.";
                return FALSE;
	}
        fclose($handle);
	return TRUE;
}

function FlushAllArp()
{
	$command = "for i in `arp -an | awk '{printf $2}' |sed 's/)/ /g' | sed 's/(/ /g'`;". ' do arp -d $i; done ';
	shell_exec($command);
}
//FlushAllArp();

function ApplySysIpMacBind()
{
	global $arp;

	$e = GetXmlIpMacBindEnabled();
	if ($e == 0)
		return ;

        $file_name = "/etc/ethers";
	$s = '';
	$list = GetXmlBindList();
	foreach ($list as $l)
	{
		if ($l['Mac'] == '')
			continue;
		
		$s .= $l['Ip']. ' '. $l['Mac']. "\n";
	}

	$ret = WriteStringToFile($file_name, $s);
	//if ($ret == FALSE)
	//	print "Error write file.";
	FlushAllArp();
	$command = $arp. " -f 1>/dev/null 2>&1";
	shell_exec($command);
}
//ApplySysIpMacBind();

?>
